package com.tinem.platform.service.security.api;

import cn.hutool.core.util.HexUtil;
import com.tinem.platform.module.pojo.vo.security.cypher.CypherReq;
import com.tinem.platform.module.pojo.vo.security.cypher.CypherRes;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @program: platform
 * @description: ${description}
 * @author: eden#can
 * @Slogan: 没有所谓失败，除非你不再尝试
 * @date: 2021-11-15 11:57
 **/
@Controller
@RequestMapping("/cypher")
public class CypherApi {

    /**
     * 简单加密
     * @param cypherReq
     * @return
     */
    @PostMapping("/encryption.api")
    @ResponseBody
    public CypherRes encryption(@RequestBody CypherReq cypherReq){

        String encryptionStr = cypherReq.getReqStr();
        String pwd = null;
        //1、 utf-8转byte[]
        byte[] bytes; // 0/1
        try {
            bytes = encryptionStr.getBytes("utf-8");
        } catch (Exception e) {
            throw new RuntimeException("消息体转byte数组异常");
        }
        //2、 正负位反 （byte数组中的1 -> -1、 32->-23）
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) ~bytes[i];
        }
        //3、 base64 encode
        pwd = HexUtil.encodeHexStr(bytes);

        CypherRes cypherRes = new CypherRes();
        cypherRes.setResStr(pwd);
        return cypherRes;
    }

    /**
     * 简单揭秘
     * @param cypherReq
     * @return
     */
    @PostMapping("/decrypt.api")
    @ResponseBody
    public CypherRes decrypt(@RequestBody CypherReq cypherReq){
        String s = null;

        byte[] decode = HexUtil.decodeHex(cypherReq.getReqStr());
        //2、 正负位反 （byte数组中的1 -> -1、 32->-23）
        for (int i = 0; i < decode.length; i++) {
            decode[i] = (byte) ~decode[i];
        }

        try {
            s = new String(decode, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }

        CypherRes cypherRes = new CypherRes();
        cypherRes.setResStr(s);
        return cypherRes;
    }
}
